
import { execSync } from "child_process";
import fs from "fs";
import {join} from "path";
const libaryName = "HONGSHU_LIB";
import os from "os";

async function createLink(targetPath) {
    try {

        var libaryPath = process.env[libaryName];
        if(!libaryPath){
            throw new Error("未配置环境变量:HONGSHU_LIB");

        };
        if (os.type() == 'Windows_NT') {
            //windows
            targetPath = join(targetPath || process.cwd(), "node_modules");
          
            let moduleExists = fs.existsSync(targetPath);
            if (moduleExists) {
                return;
            };

            fs.symlinkSync(libaryPath, targetPath, "dir")
        } else if (os.type() == 'Darwin') {
            //mac
            targetPath = join(targetPath || process.cwd());
            execSync(`ln -s ${libaryPath} ${targetPath}`)
            
        } else if (os.type() == 'Linux') {
            //Linux
            targetPath = join(targetPath || process.cwd());
            execSync(`ln -s ${libaryPath} ${targetPath}`)
        } else {
            //不支持提示
            throw new Error(`系统类型${os.type()}不支持`);
        }
        console.log('\x1b[32m%s\x1b[0m',"创建node_modules外链成功");
    } catch (error) {
        console.error(error)
        process.exit(1);
    }
}

/**
 * 确保有node_modules外链
 */
async function ensureNodeModulesLink(){
   let isExists = fs.existsSync(join(process.cwd(),"node_modules"));
   if(isExists){
    console.log("\x1b[32m%s\x1b[0m","node_modules存在，不需要创建node_modules的外链");
    return;
   }
   await createLink();
};

export {
    ensureNodeModulesLink,
    createLink
}

await ensureNodeModulesLink();